<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-left">
        <text class="header-title">设备管理</text>
        <view class="farm-selector" @tap="showFarmSelector">
          <text>{{ currentFarmName }}</text>
          <text class="iconfont icon-down"></text>
        </view>
      </view>
      <view class="header-right">
        <view class="refresh-btn" @tap="refreshDevices">
          <text class="iconfont icon-refresh"></text>
          <text class="refresh-text">刷新</text>
        </view>
        <view class="icon-btn" @tap="showFilterOptions">
          <text class="iconfont icon-filter"></text>
        </view>
      </view>
    </view>
    
    <!-- 设备类型筛选 -->
    <view class="device-filter">
      <scroll-view scroll-x="true" class="filter-scroll" show-scrollbar="false">
        <view 
          v-for="(type, index) in deviceTypes" 
          :key="index"
          class="filter-item"
          :class="{ active: currentDeviceType === type.id }"
          @tap="filterByType(type.id)"
        >
          <text class="iconfont" :class="type.icon"></text>
          <text>{{ type.name }}</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 设备统计 -->
    <view class="device-stats">
      <view class="stat-item">
        <text class="stat-value">{{ deviceStats.total }}</text>
        <text class="stat-label">总设备</text>
      </view>
      <view class="stat-item">
        <text class="stat-value online">{{ deviceStats.online }}</text>
        <text class="stat-label">在线</text>
      </view>
      <view class="stat-item">
        <text class="stat-value offline">{{ deviceStats.offline }}</text>
        <text class="stat-label">离线</text>
      </view>
      <view class="stat-item">
        <text class="stat-value warning">{{ deviceStats.warning }}</text>
        <text class="stat-label">异常</text>
      </view>
    </view>
    
    <!-- 设备列表 -->
    <view class="device-list">
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text class="iconfont icon-loading"></text>
        <text>正在加载设备列表...</text>
      </view>
      
      <!-- 错误状态 -->
      <view class="error-state" v-else-if="error">
        <text class="iconfont icon-error"></text>
        <text>{{ error }}</text>
        <view class="retry-btn" @tap="getDeviceList">重试</view>
      </view>
      
      <!-- 设备列表 -->
      <template v-else>
      <view 
        v-for="(device, index) in filteredDevices" 
          :key="device._id"
        class="device-card"
          :class="{ 'warning': device.de_status === 2 }"
          @tap="viewDeviceDetail(device._id)"
      >
          <!-- 警告图标 -->
          <text v-if="device.de_status === 2" class="iconfont icon-warning warning-icon"></text>
          
        <view class="device-icon">
            <text class="iconfont" :class="getDeviceIcon(device.de_model)"></text>
        </view>
        
        <view class="device-info">
          <view class="device-header">
              <view class="device-title-wrapper">
                <text class="device-name">{{ device.de_name || '未命名设备' }}</text>
                <text v-if="device.de_status === 2" class="warning-text">设备异常</text>
              </view>
              <view class="device-status" :class="getStatusClass(device.de_status)">
              <view class="status-dot"></view>
                <text>{{ getStatusText(device.de_status) }}</text>
            </view>
          </view>
          
          <view class="device-location">
            <text class="iconfont icon-location"></text>
              <text>{{ device.de_location || '未设置位置' }}</text>
          </view>
          
            <view class="device-data" v-if="device.de_data">
              <view v-for="(data, key) in device.de_data" :key="key" class="data-item">
              <text class="data-label">{{ getDataLabel(key) }}</text>
              <text class="data-value">{{ data.value }}{{ data.unit }}</text>
            </view>
          </view>
          
          <view class="device-footer">
              <text class="device-time">{{ device.de_lastUpdate }}</text>
            <view class="device-actions">
                <view class="action-btn" @tap.stop="toggleDevice(device._id, device.de_status)">
                <image 
                  class="action-icon" 
                    :src="device.de_status === 1 ? '/static/devices/icons8-打开-24.png' : '/static/devices/icons8-关掉-24.png'" 
                  mode="aspectFit"
                ></image>
              </view>
                <view class="action-btn" @tap.stop="showDeviceSettings(device._id)">
                <image class="action-icon" src="/static/devices/跳转.png" mode="aspectFit"></image>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 无设备提示 -->
        <view class="empty-state" v-if="!loading && !error && filteredDevices.length === 0">
        <text class="iconfont icon-empty"></text>
        <text>暂无设备</text>
        <text>请添加设备或更改筛选条件</text>
      </view>
      </template>
    </view>
    
    <!-- 添加设备按钮 -->
    <view class="add-device-btn" @tap="addNewDevice">
      <image class="add-icon" src="/static/icons8-加号-50.png" mode="aspectFit"></image>
    </view>
  </view>
</template>

<script setup lang="ts">
/// <reference types="@dcloudio/types" />
import { ref, reactive, computed, onMounted } from 'vue';

// 类型声明
interface Device {
  _id: string;
  de_name: string;
  de_model: string;
  de_location: string;
  de_status: number;
  de_data: Record<string, any>;
  de_lastUpdate: string;
  update_time: string | number;
}

interface DeviceType {
  id: string;
  name: string;
  icon: string;
}

interface Farm {
  id: number;
  name: string;
}

// 设备列表
const devices = ref<Device[]>([]);

// 农场列表
const farms = reactive<Farm[]>([
  { id: 1, name: '绿源农场1号' },
  { id: 2, name: '绿源农场2号' },
  { id: 3, name: '蔬菜大棚基地' },
  { id: 4, name: '果园基地' }
]);

// 当前选中的农场
const currentFarm = ref<number>(1);

// 当前农场名称
const currentFarmName = computed(() => {
  const farm = farms.find(f => f.id === currentFarm.value);
  return farm ? farm.name : '选择农场';
});

// 设备类型
const deviceTypes = reactive<DeviceType[]>([
  { id: 'all', name: '全部', icon: 'icon-all' },
  { id: 'sensor', name: '传感器', icon: 'icon-sensor' },
  { id: 'camera', name: '摄像头', icon: 'icon-camera' },
  { id: 'controller', name: '控制器', icon: 'icon-controller' },
  { id: 'irrigation', name: '灌溉', icon: 'icon-irrigation' },
  { id: 'light', name: '照明', icon: 'icon-light' }
]);

// 当前选中的设备类型
const currentDeviceType = ref<string>('all');

// 设备统计
const deviceStats = computed(() => {
  return {
    total: devices.value.length,
    online: devices.value.filter(device => device.de_status === 1).length,
    offline: devices.value.filter(device => device.de_status === 0).length,
    warning: devices.value.filter(device => device.de_status === 2).length
  };
});

// 过滤后的设备列表
const filteredDevices = computed(() => {
  console.log('当前设备列表:', devices.value);
  if (currentDeviceType.value === 'all') {
    return devices.value;
  } else {
    return devices.value.filter(device => device.de_model === currentDeviceType.value);
  }
});

// 页面加载状态
const loading = ref(false);
const error = ref('');

// 获取设备列表
const getDeviceList = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    console.log('开始获取设备列表');
    uni.showLoading({ title: '加载中...' });
    
    const { result } = await uniCloud.callFunction({
      name: 'getDevices',
      data: {}
    });
    console.log('云函数返回的完整结果:', result);
    
    if (result && result.code === 0) {
      if (!Array.isArray(result.data)) {
        console.error('返回的数据不是数组:', result.data);
        throw new Error('数据格式错误');
      }
      
      devices.value = result.data.map(device => ({
        _id: device._id,
        de_name: device.de_name || '未命名设备',
        de_model: device.de_model || 'unknown',
        de_location: device.de_location || '未知位置',
        de_status: typeof device.de_status === 'number' ? device.de_status : 0,
        de_data: device.de_data || {},
        de_lastUpdate: formatTime(device.update_time),
        update_time: device.update_time
      }));
      
      console.log('处理后的设备数据:', devices.value);
    } else {
      console.error('获取设备列表失败:', result.message);
      error.value = result.message || '获取设备列表失败';
      uni.showToast({
        title: error.value,
        icon: 'none'
      });
    }
  } catch (e) {
    console.error('获取设备列表出错:', e);
    error.value = e.message || '获取设备列表失败';
    uni.showToast({
      title: error.value,
      icon: 'none'
    });
  } finally {
    loading.value = false;
    uni.hideLoading();
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '未知';
  const now = new Date().getTime();
  const diff = now - new Date(timestamp).getTime();
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚';
  }
  // 小于1小时
  if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前';
  }
  // 小于24小时
  if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前';
  }
  // 大于24小时
  return Math.floor(diff / 86400000) + '天前';
};

// 刷新设备列表
const refreshDevices = async () => {
  try {
    uni.showLoading({
      title: '刷新中...',
      mask: true
    });
    
    await getDeviceList();
    
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1500
    });
  } catch (error) {
    console.error('刷新设备列表失败:', error);
    uni.showToast({
      title: '刷新失败',
      icon: 'error',
      duration: 1500
    });
  } finally {
    uni.hideLoading();
  }
};

// 按类型筛选设备
const filterByType = (typeId) => {
  currentDeviceType.value = typeId;
};

// 显示筛选选项
const showFilterOptions = () => {
  uni.showActionSheet({
    itemList: ['按状态筛选', '按添加时间排序', '按更新时间排序'],
    success: (res) => {
      uni.showToast({
        title: '筛选功能开发中',
        icon: 'none'
      });
    }
  });
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '离线',
    1: '在线',
    2: '异常'
  };
  return statusMap[status] || '未知';
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    0: 'offline',
    1: 'online',
    2: 'warning'
  };
  return statusMap[status] || 'offline';
};

// 切换设备状态
const toggleDevice = async (deviceId, currentStatus) => {
  try {
    // 如果设备处于异常状态，显示提示
    if (currentStatus === 2) {
      uni.showModal({
        title: '设备异常',
        content: '设备当前处于异常状态，请先检查设备并解除警告状态',
        showCancel: false
      });
      return;
    }
    
    const newStatus = currentStatus === 0 ? 1 : 0;
    const { result } = await uniCloud.callFunction({
      name: 'updateDeviceStatus',
      data: {
        deviceId,
        status: newStatus
      }
    });
    
    if (result && result.code === 0) {
      // 更新本地设备状态
      const device = devices.value.find(d => d._id === deviceId);
      if (device) {
        device.de_status = newStatus;
      }
    
    uni.showToast({
        title: newStatus === 1 ? '设备已开启' : '设备已关闭',
      icon: 'success'
      });
    } else {
      uni.showToast({
        title: result.message || '操作失败',
        icon: 'none'
      });
    }
  } catch (e) {
    console.error('切换设备状态失败:', e);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 查看设备详情
const viewDeviceDetail = (deviceId) => {
  uni.navigateTo({
    url: `/pages/devices/detail?id=${deviceId}`
  });
};

// 显示设备设置
const showDeviceSettings = (deviceId) => {
  try {
    // 查找当前设备
    const currentDevice = devices.value.find(d => d._id === deviceId);
    if (!currentDevice) {
      uni.showToast({
        title: '设备不存在',
        icon: 'none'
      });
      return;
    }

    // 构建URL参数
    const params = {
      id: deviceId,
      type: currentDevice.de_model,
      status: currentDevice.de_status,
      name: encodeURIComponent(currentDevice.de_name || ''),
      location: encodeURIComponent(currentDevice.de_location || '')
    };

    // 构建URL查询字符串
    const queryString = Object.entries(params)
      .map(([key, value]) => `${key}=${value}`)
      .join('&');

    // 跳转到设备设置页面
    uni.navigateTo({
      url: `/pages/devices/settings?${queryString}`,
      fail: (err) => {
        console.error('页面跳转失败:', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  } catch (error) {
    console.error('跳转设备设置页面失败:', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 添加新设备
const addNewDevice = () => {
  uni.navigateTo({
    url: '/pages/devices/add'
  });
};

// 获取设备图标
const getDeviceIcon = (type) => {
  const iconMap = {
    'sensor': 'icon-sensor',
    'camera': 'icon-camera',
    'controller': 'icon-controller',
    'irrigation': 'icon-irrigation',
    'light': 'icon-light'
  };
  return iconMap[type] || 'icon-device';
};

// 获取数据标签
const getDataLabel = (key) => {
  const labelMap = {
    'temperature': '温度',
    'humidity': '湿度',
    'moisture': '土壤湿度',
    'ph': 'pH值',
    'light': '光照',
    'waterFlow': '水流量',
    'brightness': '亮度',
    'mode': '模式'
  };
  
  return labelMap[key] || key;
};

// 页面加载时获取设备列表
onMounted(() => {
  getDeviceList();
});

// 显示农场选择器
const showFarmSelector = () => {
  uni.showActionSheet({
    itemList: farms.map(farm => farm.name),
    success: (res) => {
      currentFarm.value = farms[res.tapIndex].id;
    }
  });
};
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding-bottom: 60px;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #4CAF50;
}

.header-left {
  display: flex;
  flex-direction: column;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
  margin-bottom: 5px;
}

.farm-selector {
  display: flex;
  align-items: center;
}

.farm-selector text {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
}

.farm-selector .iconfont {
  font-size: 12px;
  margin-left: 5px;
}

.header-right {
  display: flex;
  align-items: center;
}

.refresh-btn {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  cursor: pointer;
}

.refresh-btn .iconfont {
  font-size: 16px;
  color: #ffffff;
  margin-right: 4px;
}

.refresh-btn .refresh-text {
  font-size: 14px;
  color: #ffffff;
}

.refresh-btn:active {
  background-color: rgba(255, 255, 255, 0.3);
}

.icon-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-btn .iconfont {
  font-size: 20px;
  color: #ffffff;
}

/* 设备类型筛选 */
.device-filter {
  background-color: #ffffff;
  padding: 10px 0;
  margin-bottom: 10px;
}

.filter-scroll {
  white-space: nowrap;
  padding: 0 15px;
}

.filter-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20px;
}

.filter-item:last-child {
  margin-right: 0;
}

.filter-item .iconfont {
  font-size: 24px;
  color: #999999;
  margin-bottom: 5px;
}

.filter-item text:last-child {
  font-size: 12px;
  color: #999999;
}

.filter-item.active .iconfont {
  color: #4CAF50;
}

.filter-item.active text:last-child {
  color: #4CAF50;
}

/* 设备统计 */
.device-stats {
  display: flex;
  background-color: #ffffff;
  padding: 15px;
  margin-bottom: 10px;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 5px;
}

.stat-value.online {
  color: #4CAF50;
}

.stat-value.offline {
  color: #9E9E9E;
}

.stat-value.warning {
  color: #FF9800;
}

.stat-label {
  font-size: 12px;
  color: #666666;
}

/* 设备列表 */
.device-list {
  flex: 1;
  padding: 10px;
}

.device-card {
  display: flex;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  position: relative;
  border-left: 4px solid transparent;
  transition: all 0.3s ease;
}

.device-card.warning {
  border-left-color: #FF9800;
  background-color: #FFF3E0;
}

/* 添加警告图标 */
.warning-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  color: #FF9800;
  animation: blink 1s infinite;
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.device-status.warning {
  background-color: rgba(255, 152, 0, 0.1);
}

.device-status.warning text {
  color: #FF9800;
}

.device-status.warning .status-dot {
  background-color: #FF9800;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.5); opacity: 0.5; }
  100% { transform: scale(1); opacity: 1; }
}

.device-icon {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background-color: rgba(76, 175, 80, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.device-icon .iconfont {
  font-size: 24px;
  color: #4CAF50;
}

.device-info {
  flex: 1;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.device-title-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.device-name {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.device-status {
  display: flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 10px;
  background-color: rgba(0, 0, 0, 0.05);
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 3px;
  margin-right: 4px;
}

.device-status.online .status-dot {
  background-color: #4CAF50;
}

.device-status.offline .status-dot {
  background-color: #9E9E9E;
}

.device-status.warning .status-dot {
  background-color: #FF9800;
}

.device-status text {
  font-size: 12px;
  color: #666666;
  transition: color 0.3s ease;
}

.device-status.warning text {
  font-weight: bold;
}

.device-location {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.device-location .iconfont {
  font-size: 14px;
  color: #999999;
  margin-right: 5px;
}

.device-location text:last-child {
  font-size: 14px;
  color: #666666;
}

.device-data {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.data-item {
  margin-right: 15px;
  margin-bottom: 5px;
}

.data-label {
  font-size: 12px;
  color: #999999;
  margin-right: 5px;
}

.data-value {
  font-size: 14px;
  color: #333333;
}

.device-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.device-time {
  font-size: 12px;
  color: #999999;
}

.device-actions {
  display: flex;
}

.action-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 16px;
  margin-left: 8px;
}

.action-icon {
  width: 20px;
  height: 20px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.empty-state .iconfont {
  font-size: 48px;
  color: #e0e0e0;
  margin-bottom: 15px;
}

.empty-state text:nth-child(2) {
  font-size: 16px;
  color: #999999;
  margin-bottom: 5px;
}

.empty-state text:nth-child(3) {
  font-size: 14px;
  color: #999999;
}

/* 添加设备按钮 */
.add-device-btn {
  position: fixed;
  right: 20px;
  bottom: 80px;
  width: 56px;
  height: 56px;
  border-radius: 28px;
  background-color: #F5F5F5;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 3px 10px rgba(76, 175, 80, 0.3);
}

.add-icon {
  width: 30px;
  height: 30px;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.loading-state .iconfont {
  font-size: 48px;
  color: #4CAF50;
  margin-bottom: 15px;
  animation: rotate 1s linear infinite;
}

.loading-state text {
  font-size: 14px;
  color: #666666;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 错误状态样式 */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.error-state .iconfont {
  font-size: 48px;
  color: #f44336;
  margin-bottom: 15px;
}

.error-state text {
  font-size: 14px;
  color: #666666;
  margin-bottom: 15px;
}

.retry-btn {
  padding: 8px 20px;
  background-color: #4CAF50;
  color: #ffffff;
  border-radius: 4px;
  font-size: 14px;
}

.warning-text {
  font-size: 12px;
  color: #FF9800;
  background-color: rgba(255, 152, 0, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}
</style>